package com.noahsloan.nutils.streams;

import java.io.IOException;
import java.io.InputStream;

/**
 * A CombinedInputStream concatenates multiple streams into a cohesive data
 * flow.
 * 
 * @author Noah Sloan
 * 
 */
public class CombinedInputStream extends InputStream {

    private int current; // the current stream we are reading.

    private InputStream[] streams; // all the streams

    /**
     * 
     * @param in
     *            the streams to combine, in the order they should be combined.
     */
    public CombinedInputStream(InputStream... in) {
        current = 0;
        streams = in;
    }

    @Override
    /**
     * Obeys the general contract of read. -1 indicates end of last stream.
     */
    public int read() throws IOException {
        int i = -1;
        if (current < streams.length) {
            // if we have not exhausted all the streams,read from the current
            // one
            i = streams[current].read();
            if (i == -1) {
                // if we have exhausted the current stream, try the next one
                current++;
                return read();
            }
        }
        return i;
    }

    @Override
    /**
     * Closes ALL the underlying streams, even those not read from.
     */
    public void close() throws IOException {
        for (InputStream stream : streams) {
            stream.close();
        }
    }

    @Override
    public int available() throws IOException {
        return current < streams.length ? streams[current].available() : 0;
    }
}
